<?php

namespace PhpYes\Com;


final class SingleProcessLock
{
    public static function lock($cmd, $pidFile)
    {
        $cmd = empty($cmd) ? null : trim($cmd);
        if (empty($cmd)) {
            exit(1);
        }
        $pidFile = empty($pidFile) ? null : trim($pidFile);
        if (empty($pidFile)) {
            exit(1);
        }

        if (file_exists($pidFile)) {
            $pid = file_get_contents($pidFile);
            $pid = intval($pid);
            if (empty($pid)) {
                exit(1);
            }
            $psInfo = array();
            exec("ps -p {$pid} -o pid,args | grep {$cmd}", $psInfo);
            if ($psInfo) {
                exit(1);
            }
        }
        $pid = posix_getpid();
        file_put_contents($pidFile, strval($pid));
    }
}